<template>
  <section>
    <!--列表-->
    <el-table :data="stockLists" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;" border="true">
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" prop="id" width="60" label="ID" sortable>
      </el-table-column>
      <el-table-column align="center" prop="name" label="产品名" width="150" sortable>
      </el-table-column>
      <el-table-column align="center" prop="picture" label="产品图片" width="180" >
        <template slot-scope="{row}">
          <el-image :src="row.picture[0]" fit="contain"  class="image-container-box"   :preview-src-list="row.picture" ></el-image>
        </template>
<!--        <template slot-scope="{row}">-->
<!--          <el-image class="image-container-box" :src="row.picture"></el-image>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column align="center" prop="productClassify.productClassifyName" label="产品分类" width="120" >
      </el-table-column>
      <el-table-column align="center" prop="stock" label="库存" width="120" sortable>
      </el-table-column>
      <el-table-column align="center" prop="price" label="价格" width="120" sortable>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="160" sortable>
      </el-table-column>
      <el-table-column align="center" label="操作" width="350">
        <template scope="scope">
          <el-button v-perm="'stock/upd'"  type="info" size="small" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">修改库存</el-button>
          <el-button v-perm="'stock/del'" type="danger" size="small" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"><i class=""/>删除</el-button>
          <el-button v-perm="'stock/updhost'" type="success" size="small" icon="el-icon-collection" @click="handleLog(scope.$index, scope.row)">修改记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[5, 10, 20, 50]"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:right; margin-right: 40px;"  >
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑库存" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm"  label-width="100px"  ref="editForm" :rules="editFormRules">
        <el-form-item label="产品名称:" prop="name">
          <span>{{ editForm.name }}</span>
        </el-form-item>
        <el-form-item label="现有库存量:" prop="stock">
          <span>{{ editForm.stock }}</span>
        </el-form-item>
        <el-form-item label="修改库存:"prop="updStock" >
          <el-input-number v-model="editForm.updStock"  type="number" min="0" style="width: 230px" placeholder="请输入产品库存！"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" auto-complete="off" type="textarea"
                    :rows="2"
                    placeholder="请输入此次修改理由"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--库存记录页面    -->
    <el-dialog title="库存记录" style="width:100%;" :visible.sync="logFormVisible" :close-on-click-modal="false">
      <el-table :data="stockLog" style="width: 100%"  border="true">
        <el-table-column prop="procId" label="库存id" width="80">
        </el-table-column>
        <el-table-column prop="updBefore" label="改前库存" width="100">
        </el-table-column>
        <el-table-column prop="updAfter" label="改后库存" width="100">
        </el-table-column>
        <el-table-column prop="updNum" label="修改数量" width="100">
          <template slot-scope="{ row }">
    <span :style="{ color: row.updNum >= 0 ? 'green' : 'red' }">
      {{ row.updNum > 0 ? '增加' : row.updNum < 0 ? '减少' : '未添加' }}{{ Math.abs(row.updNum) }}
    </span>
          </template>
        </el-table-column>
        <el-table-column prop="updUser" label="修改人" width="110">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150">
        </el-table-column>
        <el-table-column prop="updUser" label="修改人" width="100">
        </el-table-column>
        <el-table-column prop="updTime" label="修改时间" width="150">
        </el-table-column>
      </el-table>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" :label-position="labelPosition"  label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="产品名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="classifyId">
        <el-select v-model="addForm.classifyId" placeholder="请选择该分类">
          <el-option v-for="item in classfiy"
                     :label="item.productclassifyName"
                     :value="item.id">
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品价格">
          <el-input v-model="addForm.price" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品库存">
          <el-input v-model="addForm.stock" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="添加图片">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=1
              accept=".jpg,.png,.gif"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>
          </el-upload>

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      //1.分页查询的相关数据
      stockLists: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5,10, 20, 50], // 可选择的每页条数
      listLoading: false,
      sels: [],//列表选中列
      selectedSearchField:'',
      //2.高级查询相关数据
      keyword: '',
      editFormVisible: false,//编辑界面是否显示
      logFormVisible:false,//库存记录页面
      editLoading: false,
      editFormRules: {
        remark: [
          {required: true, message: '请输入修改备注！', trigger: 'blur'}
        ]
      },
      //3编辑界面数据
      editForm: {
          stock: '',
        updStock:'',
        remark:'',
        upuser:''
      },
      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ]
      },
      stockLog: [],
      //4新增界面数据
      addForm: {
        id: null,
        name: '',
        picture: '',
        classifyId: '',
        stock: '',
        price: '',
        UpdateTime: ''
      },

      fileList: [],
      labelPosition: 'left',
      classfiy:[],
    }
  },
  methods: {
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.getstockLists();
    },
    //1.分页获取库存列表
    getstockLists() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/stock", para).then((res) => {
        this.totals = res.data.total;
        this.stockLists = res.data.records.map(product => {
          return {
            ...product,
            label: product.label ? product.label.split(' ') : [],// 将空格分隔的字符串转换为数组
            picture:product.picture? product.picture.split(','):[],
            detailsPicture:product.detailsPicture? product.detailsPicture.split(','):[],
          };
        });
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试!!!【400,404】")
      });
    },
//获取分类
    getclassify() {
      this.$http.get("/productClassify").then(res=>{
        this.classfiy = res.data;
      })
    },

    //2.点击分页实现
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getstockLists();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置当前页码为1
      this.getstockLists();
    },
    //3.关键字查询
    keywordQuery() {
      //假如当前页不在第一页，防止高级查询没有那么多页的时候出现空数据的问题
      this.currentPage = 1;
      this.getstockLists();
    },

    //5.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/stock/" + row.id).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getstockLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });
    },




    //6.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },

    //7.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/stock", ids).then(res => {
          if (res.data.success) {
            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            //当删除最后一页的所有数据，并且不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - this.sels.length) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getstockLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });

    },

    //8.显示编辑界面
    handleEdit: function (index, row) {
      this.editForm = Object.assign({}, row);
      // console.log('数据:查询', this.editForm)
      this.editFormVisible = true;
      // this.getDepartments();
    },
    //8.1 显示库存记录界面
    handleLog: function (index, row) {
      this.logFormVisible = true;

      this.$http.get("/stockLog/"+row.id).then(res=>{
        this.stockLog = res.data;
      })
    },


    //9.显示新增界面
    handleAdd: function () {
      this.addForm = {};
      this.addFormVisible = true;

    },

    //10.提交编辑数据
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            this.editForm.stock=this.editForm.updStock;
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            const user1 = logininfo.username;
            this.editForm.upuser = user1;
            let para = Object.assign({}, this.editForm);
           // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            para.picture = para.picture.join(','); // 将标签数组转换为字符串
            this.$http.put("/stock/upd", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              this.getstockLists();
            });
          });
        }
      });
    },

    //11.提交
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = Object.assign({}, this.addForm);
            this.$http.put("/stock/add", para).then(res => {

              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.addLoading = false;
              this.addFormVisible = false;
              this.getstockLists();
            });
          });
        }
      });
    },
    //文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.picture = response.resultObj;
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },
  },

  mounted() {
    this.getstockLists();
    this.getStockLog();
  }
}

</script>

<style scoped>

</style>